package com.tencent.iov.cowin.befsale.clue.service.cus.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.request.CusUnbindRequest;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.CusUnbindResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.CustomerExtAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.DealerCustomerAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.*;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerBehaviorResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerExtResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerWithExtResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.MdQueryClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryCustomerEmployeeRelRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.CustomerBaseResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.CustomerEmployeeRelResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.EmployeeResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.SecondaryDealerResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdwrite.MdWriteClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdwrite.request.AddSecondaryDealerRequest;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.Clue;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueCustomerCollect;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueIntentionVehicle;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.ClueTodoRel;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.*;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.*;
import com.tencent.iov.cowin.befsale.clue.repository.cus.DealerCustomerManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueCustomerCollectService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueService;
import com.tencent.iov.cowin.befsale.clue.service.clue.ClueTodoRelService;
import com.tencent.iov.cowin.befsale.clue.service.cus.*;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import com.tencent.iov.cowin.befsale.clue.service.cus.*;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import com.tencent.iov.cowin.befsale.clue.value.utils.CustomerUtil;
import com.tencent.iov.cowin.befsale.clue.value.utils.ResponseUtil;
import com.software.boot.common.entity.Response;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.PageRequest;
import com.software.boot.common.model.dao.PageResponse;
import com.software.boot.common.util.BeanUtil;
import com.software.boot.common.util.EmptyUtils;
import com.software.boot.common.util.ValidateUtils;
import com.software.common.config.SearchLocalHeader;
import com.software.common.enums.DeleteEnum;
import com.software.common.enums.SCRMRequestHeaderEnum;
import com.software.common.utils.BasePropertyInjection;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.*;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Describe: 经销商客户表主表+客户好友关联表_Service实现层
 * @author: xiamu
 * @created: 2021-12-21 17:29:48
 * @version: 1.0
 */
@Service
public class DealerCustomerServiceImpl implements DealerCustomerService {

    @Autowired
    private DealerCustomerManager dealerCustomerManager;
    @Autowired
    private CustomerExtService customerExtService;
    @Autowired
    private OemCustomerService oemCustomerService;
    @Autowired
    private DealerCustomerService dealerCustomerService;
    @Autowired
    private ClueCustomerCollectService clueCustomerCollectService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private MdQueryClient mdQueryClient;
    @Autowired
    private CustomerBehaviorService customerBehaviorService;
    @Autowired
    private MdWriteClient mdWriteClient;
    @Autowired
    private DealerCustomerFollowPlanService dealerCustomerFollowPlanService;
    @Autowired
    private ClueService clueService;
    @Autowired
    private ClueTodoRelService clueTodoRelService;


    /**
     * 通过ID获取详细信息
     *
     * @param: id 主键ID
     * @return: DealerCustomer对象
     */
    @Override
    public CustomerResponse getDetailById(Long id) {
        //验证请求参数
        ValidateUtils.checkLongGTZero(id, "ID不能为空或小于0");
        //处理业务
        DealerCustomer dealerCustomer = dealerCustomerManager.getDetailById(id);
        if (EmptyUtils.isEmpty(dealerCustomer)) {
            return null;
        }
        CustomerResponse customerResponse = BeanUtil.copy(dealerCustomer, CustomerResponse.class);

        CustomerExt queryCustomerExt = new CustomerExt();
        queryCustomerExt.setCusId(dealerCustomer.getId());
        queryCustomerExt.setDealerId(dealerCustomer.getDealerId());
        queryCustomerExt.setCustomerType(CustomerExtCustomerTypeEnum.DEALER_CUSTOMER.getCode());
        CustomerExt customerExt = customerExtService.getOneByParam(queryCustomerExt);
        //基本标签信息枚举
        if (EmptyUtils.isNotEmpty(customerExt)) {
            DealerCustomerAssembler.initCustomerResponse(customerResponse, customerExt);
        }

        //基本标签的拼接 + 渠道与活动
        customerResponse.setCustomerCodeStr(customerService.getClueCustomerTagStr(customerResponse));

        //行为标签数据
        CustomerBehavior queryBehavior = new CustomerBehavior();
        queryBehavior.setCusType(CustomerTypeEnum.CUSTOMER_TYPE_DEALER.getCode());
        queryBehavior.setDealerCusId(dealerCustomer.getId());
        queryBehavior.setCorpId(dealerCustomer.getCorpId());
        queryBehavior.setTenantId(dealerCustomer.getTenantId());
        queryBehavior.setDealerId(dealerCustomer.getDealerId());
        CustomerBehavior customerBehavior = customerBehaviorService.statisticalByCusId(queryBehavior);
        if (EmptyUtils.isNotEmpty(customerBehavior)) {
            customerResponse.setCustomerBehavior(JSON.toJSONString(customerBehavior));
        }

        //二网信息
        fillSecondaryInfo(customerResponse);
        return customerResponse;
    }

    private void fillSecondaryInfo(CustomerResponse customerResponse) {
        if (EmptyUtils.isEmpty(customerResponse.getDealerSecondaryId()) || customerResponse.getDealerSecondaryId() <= 0) {
            return;
        }
        Response<SecondaryDealerResponse> secondaryResponse = mdQueryClient.getSecondaryDealerById(customerResponse.getDealerSecondaryId());
        if (EmptyUtils.isNotEmpty(secondaryResponse) && EmptyUtils.isNotEmpty(secondaryResponse.getData())) {
            customerResponse.setDealerSecondaryName(secondaryResponse.getData().getName());
        }
    }

    /**
     * 单条数据插入DealerCustomer
     *
     * @param request 添加经销商客户请求参数
     * @return 插入的条数
     */
    @Override
    public Long insert(AddDealerCustomerRequest request) {
        String noHeaderTenantId=request.getTenantId();
        String noHeaderCorpId=request.getCorpId();
        String noHeaderDealerId=request.getDealerId();

        DealerCustomer addDealerCustomer = DealerCustomerAssembler.transformVOToPO(request, DealerCustomer.class);
        //补偿录入信息
        BasePropertyInjection.savePropertyInjection(addDealerCustomer);

        //检查逻辑 参数是否存在 与 对应经销商客户是否已存在
        ValidateUtils.checkEmptyStr(addDealerCustomer.getDealerId(), "经销商ID为空");
        ValidateUtils.checkEmptyStr(addDealerCustomer.getOneId(), "客户oneID为空");
        DealerCustomer dealerRequest = DealerCustomer.builder()
                .dealerId(addDealerCustomer.getDealerId())
                .oneId(addDealerCustomer.getOneId())
                .deleted(DeletedEnum.EXIST.getCode())
                .build();
        DealerCustomer existDealerCustomer = dealerCustomerManager.getOneByParam(dealerRequest);
        if (EmptyUtils.isNotEmpty(existDealerCustomer)) {
            throw new BusinessException(NEError.DATA_EXIST, "数据已存在");
        }

        //保存二网信息并且更新经销商客户信息
        if (EmptyUtils.isEmpty(request.getDealerSecondaryId()) || request.getDealerSecondaryId() <= 0) {
            Long dealerSecondaryId = getDealerSecondaryId(request.getDealerSecondaryId(), request.getDealerSecondaryName(),request.getDealerSecondaryLevel(),
                    noHeaderTenantId,noHeaderCorpId,noHeaderDealerId);
            addDealerCustomer.setDealerSecondaryId(dealerSecondaryId);
        }
        // 处理业务
        int result = dealerCustomerManager.insert(addDealerCustomer);
        if (result < 1) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "保存失败");
        }
        //更新数据
        return addDealerCustomer.getId();
    }

    /**
     * 批量插入DealerCustomer
     *
     * @param requests 批量保存经销商客户信息
     * @return 批量插入的条数
     */
    @Override
    public int insertBatch(List<DealerCustomer> requests) {
        //验证请求参数
        if (EmptyUtils.isEmpty(requests)) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_EMPTY, "数据参数为null");
        }
        //处理业务
        return dealerCustomerManager.insertBatch(requests);
    }

    /**
     * 单条DealerCustomer更新
     *
     * @param request 经销商客户更新请求参数
     * @return 更新的条数
     */
    @Override
    public int update(UpdateCustomerRequest request) {
        //验证请求参数
        DealerCustomer updateDealerCustomer = DealerCustomerAssembler.transformVOToPO(request, DealerCustomer.class);
        //成功更新客户经销商信息
        return dealerCustomerManager.update(updateDealerCustomer);
    }


    /**
     * 通过ID删除数据
     *
     * @param request 删除参与（主键ID）
     * @return 删除的条数
     */
    @Override
    public int delete(DeleteDealerCustomerRequest request) {
        //检查参数
        ValidateUtils.checkIntNotNullAndGTZero(request.getId().intValue(), "ID不能为空或小于0");
        //处理业务
        DealerCustomer dealerCustomer = DealerCustomer.builder()
                .id(request.getId())
                .deleted(DeletedEnum.VANISH.getCode())
                .build();
        return dealerCustomerManager.update(dealerCustomer);
    }

    /**
     * 根据条件查询对象对象list列表
     *
     * @param request 查询参数
     * @return 查询结果
     */
    @Override
    public List<CustomerResponse> getListByParam(QueryCustomerRequest request) {
        request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        //转化数据
        DealerCustomer dealerCustomer = DealerCustomerAssembler.transformVOToPO(request, DealerCustomer.class);
        //查询数据
        List<DealerCustomer> dealerCustomers = dealerCustomerManager.getListByParam(dealerCustomer);
        if (EmptyUtils.isNotEmpty(dealerCustomers)) {
            return BeanUtil.copyByList(dealerCustomers, CustomerResponse.class);
        }
        return Lists.newArrayList();
    }

    /**
     * 根据条件查询对象list记录
     *
     * @param request 分页查询
     * @return 分页对象
     */
    @Override
    public PageResponse<DealerCustomer> getPageByParam(PageRequest<DealerCustomer> request) {
        //验证请求参数
        ValidateUtils.checkObjNull(request, "请求参数不能为空");

        //可以设置排序 query.orderByCreatedTime(true);
        DealerCustomer queryDealerCustomer = request.getParamData();
        queryDealerCustomer.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        queryDealerCustomer.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        queryDealerCustomer.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));

        //处理业务
        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());
        Page<DealerCustomer> queryPageList = dealerCustomerManager.getPageByParam(queryDealerCustomer, rowBounds);
        PageResponse<DealerCustomer> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), DealerCustomer.class));
        // 返回结果
        return pageResponse;
    }

    /**
     * 根据条件查询单个对象
     *
     * @param request 查询参数
     * @return 单个经销商客户数据
     */
    @Override
    public CustomerResponse getOneByParam(QueryCustomerRequest request) {
        ValidateUtils.checkObjNull(request, "查询参数为null");
        DealerCustomer queryDealer = DealerCustomerAssembler.transformVOToPO(request, DealerCustomer.class);

        request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        DealerCustomer dealerCustomer = dealerCustomerManager.getOneByParam(queryDealer);
        if (EmptyUtils.isNotEmpty(dealerCustomer)) {
            return BeanUtil.copy(dealerCustomer, CustomerResponse.class);
        }
        return null;
    }

    @Override
    public List<DealerCustomer> checkDealerCustomerPhone(DealerCustomer dealerCustomer) {
        return dealerCustomerManager.checkDealerCustomerPhone(dealerCustomer);
    }

    @Override
    public List<DealerCustomer> checkDealerCustomerOneId(DealerCustomer dealerCustomer) {
        return dealerCustomerManager.checkDealerCustomerOneId(dealerCustomer);
    }

    /**
     * 获取客户转线索的数量
     * add by zly
     * 2022-01-15
     *
     * @param clueDataRequest 参数
     * @return 查询结果
     */
    @Override
    public Long getEmpBindCount(ClueIntentionGradeDataRequest clueDataRequest) {
        return dealerCustomerManager.getEmpBindCount(clueDataRequest);
    }

    /**
     * 根据手机号查询客户信息
     * add by zly
     * 2022-01-18
     *
     * @param request 参数
     * @return 查询结果
     */
    @Override
    public CustomerWithExtResponse getCustomerInfoWithPhone(QueryCustomerRequest request) {
        CustomerWithExtResponse cusRes = null;
        String dealerId = request.getDealerId();
        //1:获取客户基本信息， 经销商为空或者为0说明是要查总部客户，否则则是查经销商客户
        DealerCustomer customer = dealerCustomerManager.getCustomerInfoWithPhone(request);
        if (customer != null) {
            cusRes = new CustomerWithExtResponse();
            CustomerResponse customerResponse = BeanUtil.copy(customer, CustomerResponse.class);
            //赋值用户基本信息
            cusRes.setCustomerResponse(customerResponse);
            //2：获取客户扩展信息
            CustomerExt requestExt = new CustomerExt();
            requestExt.setCusId(customer.getId());
            requestExt.setTenantId(request.getTenantId());
            requestExt.setCorpId(request.getCorpId());
            requestExt.setDealerId(dealerId);
            CustomerExt customerExt = customerExtService.getOneByParam(requestExt);
            if (customerExt != null) {
                CustomerExtResponse customerExtResponse = BeanUtil.copy(customerExt, CustomerExtResponse.class);
                cusRes.setCustomerExtResponse(customerExtResponse);
            }
            //获取客户行为信息
            CustomerBehavior behaviorRequest = new CustomerBehavior();
            behaviorRequest.setTenantId(request.getTenantId());
            behaviorRequest.setCorpId(request.getCorpId());
            behaviorRequest.setDealerId(dealerId);
            behaviorRequest.setDeleted(DeletedEnum.EXIST.getCode());
            //经销商为空或者为0说明是要查总部客户，否则则是查经销商客户
            if (StringUtils.isEmpty(dealerId) || "0".equals(dealerId)) {
                behaviorRequest.setOemCusId(customer.getId());
                behaviorRequest.setCusType(CustomerTypeEnum.CUSTOMER_TYPE_OEM.getCode());
            } else {
                behaviorRequest.setDealerCusId(customer.getId());
                behaviorRequest.setCusType(CustomerTypeEnum.CUSTOMER_TYPE_DEALER.getCode());
            }
            CustomerBehavior behaviorCustomer = customerBehaviorService.statisticalByCusId(behaviorRequest);
            if (behaviorCustomer != null) {
                CustomerBehaviorResponse customerBehaviorRes = BeanUtil.copy(behaviorCustomer, CustomerBehaviorResponse.class);
                cusRes.setCustomerBehaviorResponse(customerBehaviorRes);
            }
        }
        return cusRes;
    }

    @Override
    public Integer findClueByEmpId(Long empId) {
        //验证请求参数
        if (EmptyUtils.isEmpty(empId)) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_EMPTY, "empId为null");
        }

        Response<EmployeeResponse> response = mdQueryClient.getDetailById(empId);
        if (!Response.CODE_SUCCESS.equals(response.getCode()) || EmptyUtils.isEmpty(response.getData())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "未查询到成员");
        }


        QueryCustomerRequest request = new QueryCustomerRequest();
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        request.setFollowEmpId(empId);
        if( EmptyUtils.isEmpty(response.getData().getDealerId()) || response.getData().getDealerId().equals("0")){
            List<CustomerResponse>  crList =   oemCustomerService.getListByParam(request);
            return crList.size();
        }else{
            DealerCustomer req =  BeanUtil.copy(request,DealerCustomer.class);
            List<DealerCustomer> dcList =  dealerCustomerManager.getListByParam(req);
            return dcList.size();
        }
    }

    @Override
    public Boolean updateDealerCustomer(UpdateCustomerRequest updateCustomer) {
        ValidateUtils.checkObjNull(updateCustomer, "参数信息为null");
        ValidateUtils.checkLongGTZero(updateCustomer.getId(), "经销商客户主键Id参数为null");
        DealerCustomer existCustomer = dealerCustomerManager.getDetailById(updateCustomer.getId());
        ValidateUtils.checkObjNull(existCustomer, "经销商客户信息不存在");
        DealerCustomerAssembler.initUpdateCustomerRequest(updateCustomer);
        String followEmpId = existCustomer.getFollowEmpId().toString();
        if (EmptyUtils.isNotEmpty(existCustomer.getFollowEmpId()) && !followEmpId.equals(updateCustomer.getUpdatedBy())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "请操作自己跟进的线索信息");
        }

        //保存客户标签信息 bef_customer_ext
        CustomerExt customerExt = CustomerExtAssembler.transformVOToPO(updateCustomer, CustomerExt.class);
        if (EmptyUtils.isEmpty(customerExt)) {
            return true;
        }
        customerExt.setCusId(updateCustomer.getId());
        customerExt.setCustomerType(CustomerTypeEnum.CUSTOMER_TYPE_DEALER.getCode());
        Long extId = customerExtService.insertOrUpdateCustomerExt(customerExt);
        if (EmptyUtils.isEmpty(extId) || extId <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "经销商客户扩展信息处理失败");
        }

        //二网处理
        Long dealerSecondaryId = getDealerSecondaryId(updateCustomer.getDealerSecondaryId(), updateCustomer.getDealerSecondaryName(),updateCustomer.getDealerSecondaryLevel(),
                updateCustomer.getTenantId(),updateCustomer.getCorpId(),updateCustomer.getDealerId());
        updateCustomer.setDealerSecondaryId(dealerSecondaryId);

        //更新客户基本信息 bef_dealer_customer
        DealerCustomer updateDealerCustomer = DealerCustomerAssembler.transformVOToPO(updateCustomer, DealerCustomer.class);
        if (EmptyUtils.isNotEmpty(updateDealerCustomer)) {
            BasePropertyInjection.updatePropertyInjection(updateDealerCustomer);
            int updateOemResult = dealerCustomerManager.update(updateDealerCustomer);
            if (updateOemResult <= 0) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "更新经销商客户信息失败");
            }
        }
        return true;
    }

    private Long getDealerSecondaryId(Long dealerSecondaryId, String dealerSecondaryName,String dealerSecondaryLevel,
                                      String noHeaderTenantId,String noHeaderCorpId,String noHeaderDealerId ) {
        if (EmptyUtils.isNotEmpty(dealerSecondaryId) && dealerSecondaryId > 0) {
            return dealerSecondaryId;
        }
        if (EmptyUtils.isEmpty(dealerSecondaryName)) {
            return null;
        }
        AddSecondaryDealerRequest secondRequest = new AddSecondaryDealerRequest();
        secondRequest.setName(dealerSecondaryName);
        String dealerId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode());
        if (EmptyUtils.isNotEmpty(dealerId)) {
            secondRequest.setDealerId(Long.parseLong(dealerId));
        }
        secondRequest.setCode("*");
        secondRequest.setLevel(StringUtils.isEmpty(dealerSecondaryLevel)?"SECONDARY_SECOND_LEVEL_7":dealerSecondaryLevel);
        secondRequest.setRemark("线索跟进修改-添加二网");
        secondRequest.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        secondRequest.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        if(StringUtils.isEmpty(secondRequest.getTenantId())){
            secondRequest.setTenantId(noHeaderTenantId);
        }
        if(StringUtils.isEmpty(secondRequest.getCorpId())){
            secondRequest.setCorpId(noHeaderCorpId);
        }
        if(StringUtils.isEmpty(secondRequest.getDealerId())&&!StringUtils.isEmpty(noHeaderDealerId)){
            secondRequest.setDealerId(Long.parseLong(noHeaderDealerId));
        }
        Response<Long> secondResponse = mdWriteClient.insert(secondRequest);
        if (EmptyUtils.isEmpty(secondResponse) || EmptyUtils.isEmpty(secondResponse.getData()) || secondResponse.getData() <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "保存二网信息失败");
        }
        return secondResponse.getData();
    }


    @Override
    public List<CustomerBaseResponse> findCustomerBaseList() {
        Long empId = Long.valueOf(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode()));
        List<Long> customerBaseIds = findCustomerByFollowEmpId(empId);

        //外部联系人成员关联表
        QueryCustomerEmployeeRelRequest queryCustomerEmployeeRelRequest = new QueryCustomerEmployeeRelRequest();
        queryCustomerEmployeeRelRequest.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        queryCustomerEmployeeRelRequest.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        queryCustomerEmployeeRelRequest.setEmpId(empId);
        List<CustomerEmployeeRelResponse> customerEmployeeRelList = mdQueryClient.getListByParam(queryCustomerEmployeeRelRequest).getData();

        if (EmptyUtils.isEmpty(customerEmployeeRelList)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "成员顾客关联信息为空");
        }
        Map<Long, Date> customerEmployeeMap = customerEmployeeRelList.stream().collect(Collectors.toMap(CustomerEmployeeRelResponse::getCustomerId, CustomerEmployeeRelResponse::getCusCreateTime, (v1, v2) -> v2));


        //外部联系人标签记录表
        List<Long> cusBaseId = customerEmployeeRelList.stream().map(CustomerEmployeeRelResponse::getCustomerId).collect(Collectors.toList());
        List<String> cusBaseIds = cusBaseId.stream().map(String::valueOf).collect(Collectors.toList());
        //外部联系人
        Response<List<CustomerBaseResponse>> cusBaseList = mdQueryClient.getCustomerByIds(cusBaseIds);

        if (!ResponseUtil.isSuccess(cusBaseList)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, cusBaseList.getMsg());
        }

        //去掉已跟进客户。返回能绑定客户
        return cusBaseList.getData().stream().filter(cbase -> {
            for (Long cids : customerBaseIds) {
                if (cbase.getId().equals(cids)) {
                    return false;
                }
            }
            cbase.setAddQwTime(customerEmployeeMap.get(cbase.getId()));
            return true;
        }).collect(Collectors.toList());
    }

    /**
     * 查询总部或者经销商跟进未绑定客户列表
     *
     * @param request 参数
     * @return 未绑定客户信息
     */
    @Override
    public List<CusUnbindResponse> findOemOrDealerCusUnbind(CusUnbindRequest request) {

        //入参当前人信息
        String empIdStr = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode());
        //验证请求参数
        ValidateUtils.checkObjNull(empIdStr, "获取当前用户信息empID为空");
        List<CusUnbindResponse> curList;
        Long empId = Long.valueOf(empIdStr);
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        request.setFollowEmpId(empId);
        //判断经销商和总部
        if (CustomerUtil.isDealer()) {
            request.setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));
            curList = dealerCustomerManager.findDealerCusUnbind(request);
        } else {
            curList = dealerCustomerManager.findOemCusUnbind(request);
        }

        return curList;
    }

    /**
     * 查询总部或者经销商跟进未绑定客户列表
     *
     * @param request 参数
     * @return 未绑定客户信息
     */
    @Override
    public PageResponse<CusUnbindResponse> findOemOrDealerCusUnbindList(PageRequest<CusUnbindRequest> request) {
        //入参当前人信息
        String empIdStr = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode());
        //验证请求参数
        ValidateUtils.checkObjNull(empIdStr, "获取当前用户信息empID为空");
        List<CusUnbindResponse> curList;
        Long empId = Long.valueOf(empIdStr);
        request.getParamData().setDeleted(DeleteEnum.INIT.getFlag());
        request.getParamData().setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.getParamData().setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        request.getParamData().setFollowEmpId(empId);
        //判断经销商和总部
        if (CustomerUtil.isDealer()) {
            request.getParamData().setDealerId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode()));


            PageRequest<DealerCustomer> dcRequest = new PageRequest<DealerCustomer>();
            dcRequest = DealerCustomerAssembler.transformVOToPOPage(request,DealerCustomer.class);
            //可以设置排序 query.orderByCreatedTime(true);

            //处理业务
            RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());
            Page<DealerCustomer> queryPageList = dealerCustomerManager.getPageByParam(dcRequest.getParamData(), rowBounds);

            if (EmptyUtils.isEmpty(queryPageList.getResult())) {
                throw new BusinessException(NEError.METHOD_ARGUMENT_EMPTY, "没有可绑定线索客户");
            }

            List<Long> cusIdList =  queryPageList.getResult().stream().filter(dc-> EmptyUtils.isNotEmpty(dc.getExternalUserid())).map(DealerCustomer::getId).collect(Collectors.toList());

            QueryCustomerFollowPlanRequest req = new QueryCustomerFollowPlanRequest();
            req.setCusIds(cusIdList);
            List<DealerCustomerFollowPlan>  dcfpList = dealerCustomerFollowPlanService.getListByParam(req);
            Clue clue = new Clue();
            clue.setCusIds(cusIdList);
            clue.setIsActive(0);//查询活跃的
            List<Clue>  clueList = clueService.getListByParam(clue);

            ClueIntentionVehicle cvRequest = new ClueIntentionVehicle();
//            clueIntentionVehicleService.getListByParam();

            // request.setOrderFields(com.google.common.collect.Lists.newArrayList(new OrderField("id", "DESC")));





//            curList = dealerCustomerManager.findDealerCusUnbind(request);
        } else {

//            curList = dealerCustomerManager.findOemCusUnbind(request);
        }
        PageResponse<CusUnbindResponse> prcur = new PageResponse<CusUnbindResponse>();
        return prcur;
    }

    @Override
    public Boolean bindingCustomer(UpdateCustomerRequest updateCustomer) {
        //入参当前人信息
        String empIdStr = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode());
        //验证请求参数
        ValidateUtils.checkObjNull(empIdStr, "获取当前用户信息empID为空");
        List<CusUnbindResponse> curList;
        Long empId = Long.valueOf(empIdStr);

        if (EmptyUtils.isEmpty(updateCustomer.getExternalUserid()) || EmptyUtils.isEmpty(updateCustomer.getCustomerBaseId())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "外部联系人id或主数据id为空");
        }

        if (EmptyUtils.isEmpty(updateCustomer.getId())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "客户id为空");
        }
        //如果绑定线索的跟进人为空，绑定当前人
        if (EmptyUtils.isEmpty(updateCustomer.getFollowEmpId()) || updateCustomer.getFollowEmpId() == -1) {
            updateCustomer.setFollowEmpId(empId);
        }


        String dealerId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode());

        //维护宽表 宽表数据组合CusId  通过客户id去查宽表。如果是经销商通过客户id加当前经销商
        ClueCustomerCollect request = new ClueCustomerCollect();
        //where查询条件参数
        request.setCusId(updateCustomer.getId());
        //根据客户入参数据判断是否完善字段
        if (EmptyUtils.isNotEmpty(updateCustomer.getExternalUserid())) {
            updateCustomer.setBindTime(new Date());
        }
        //查询经销商或者总部
        BasePropertyInjection.updatePropertyInjection(updateCustomer);
        if (!CustomerUtil.isDealer()) {
            oemCustomerService.update(updateCustomer);
        } else {
            DealerCustomer updateDealerCustomer = BeanUtil.copy(updateCustomer, DealerCustomer.class);
            dealerCustomerManager.update(updateDealerCustomer);
            //where查询条件参数 维护宽表经销商处理
            if (EmptyUtils.isEmpty(dealerId)) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "当前为经销商客户，经销商id不能为空");
            }
            request.setDealerId(dealerId);
        }


        //维护宽表
        //修改参数
        request.setFirendStaus(CustomerFirendStausEnum.BOUND.getCode());
        request.setCustomerBaseId(updateCustomer.getCustomerBaseId());
        request.setExternalUserid(updateCustomer.getExternalUserid());
        request.setAvatar(updateCustomer.getAvatar());
        request.setQwName(updateCustomer.getQwName());
        //修改参数END
        //where查询条件参数
        BasePropertyInjection.updatePropertyInjection(request);
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        clueCustomerCollectService.updateByCusIdsAndDealerId(request);
        return true;
    }


    @Override
    public Boolean bindingCustomerTodo(UpdateCustomerRequest updateCustomer) {
        //入参当前人信息
        String empIdStr = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode());
        //验证请求参数
        ValidateUtils.checkObjNull(empIdStr, "获取当前用户信息empID为空");

        if (EmptyUtils.isEmpty(updateCustomer.getExternalUserid()) || EmptyUtils.isEmpty(updateCustomer.getCustomerBaseId())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "外部联系人id或主数据id为空");
        }

        if (EmptyUtils.isEmpty(updateCustomer.getId())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "待办id为空");
        }
        ClueTodoRel rel = new ClueTodoRel();
        rel.setTodoId(updateCustomer.getId());
        rel.setDeleted(DeleteEnum.INIT.getFlag());
        ClueTodoRel todoRel = clueTodoRelService.getOneByParam(rel);
        if(todoRel == null){
            throw new BusinessException(NEError.BUSINESS_ERROR, "待办id查询数据为空");
        }
        //查询线索
        Clue clue = clueService.getDetailById(todoRel.getBusinessId());
        if(clue == null){
            throw new BusinessException(NEError.BUSINESS_ERROR, "查询线索数据为空");
        }
        //待办ID转为cusID
        updateCustomer.setId(clue.getCusId());
        Boolean aBoolean = bindingCustomer(updateCustomer);
        if(aBoolean){
            //完成待办
            clueTodoRelService.updateClueTodoTask(MsgTodoEnum.ADD_FRIEND.getCode(),clue.getId(),empIdStr);
        }
        return true;
    }

    @Override
    public Integer cusIsBinging(String externalUserid) {
        //入参当前人信息
        String empIdStr = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode());
        //验证请求参数
        ValidateUtils.checkObjNull(externalUserid, "外部联系人id为空");
        ValidateUtils.checkObjNull(empIdStr, "获取当前用户信息empID为空");

        Long empId = Long.valueOf(empIdStr);

        //是否是经销商
        if (CustomerUtil.isDealer()) {
            DealerCustomer request = new DealerCustomer();
            request.setDeleted(DeleteEnum.INIT.getFlag());
            request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
            request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
            request.setExternalUserid(externalUserid);
            String dealerId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode());
            if (EmptyUtils.isEmpty(dealerId)) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "当前为经销商客户，经销商id不能为空");
            }
            request.setDealerId(dealerId);
            DealerCustomer dc = dealerCustomerManager.getOneByParam(request);
            if (EmptyUtils.isEmpty(dc)) {
                //未绑定
                return CustomerBingStausEnum.UNBOUND.getCode();
            } else {
                //已绑定为分配跟进人
                if (EmptyUtils.isEmpty(dc.getFollowEmpId())) {
                    return CustomerBingStausEnum.FOLLOWNULL.getCode();
                }
                //已绑定客户是否自己跟进中
                if (dc.getFollowEmpId().equals(empId)) {
                    return CustomerBingStausEnum.MYBOUND.getCode();
                } else {
                    return CustomerBingStausEnum.BOUND.getCode();
                }
            }
        } else {
            OemCustomer request = new OemCustomer();
            request.setDeleted(DeleteEnum.INIT.getFlag());
            request.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
            request.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
            request.setExternalUserid(externalUserid);
            CustomerResponse cr = oemCustomerService.getOneByParam(request);
            //未绑定
            if (EmptyUtils.isEmpty(cr)) {
                return CustomerBingStausEnum.UNBOUND.getCode();
            } else {
                //已绑定为分配跟进人
                if (EmptyUtils.isEmpty(cr.getFollowEmpId())) {
                    return CustomerBingStausEnum.FOLLOWNULL.getCode();
                }
                //已绑定客户是否自己跟进中
                if (cr.getFollowEmpId().equals(empId)) {
                    return CustomerBingStausEnum.MYBOUND.getCode();
                } else {
                    return CustomerBingStausEnum.BOUND.getCode();
                }
            }
        }
    }

    public List<Long> findCustomerByFollowEmpId(Long empId) {
        List<Long> customerBaseIds;

        //封装公共入参
        QueryCustomerRequest queryCustomerRequest = new QueryCustomerRequest();
        queryCustomerRequest.setFollowEmpId(empId);
        queryCustomerRequest.setDeleted(DeleteEnum.INIT.getFlag());
        queryCustomerRequest.setCorpId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_CORP_ACCOUNTID.getCode()));
        queryCustomerRequest.setTenantId(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_TENANTID.getCode()));
        List<CustomerResponse> customerResponses;
        //查询经销商或者总部
        if (!CustomerUtil.isDealer()) {

            customerResponses = oemCustomerService.getListByParam(queryCustomerRequest);
        } else {
            customerResponses = dealerCustomerService.getListByParam(queryCustomerRequest);
        }
        if (EmptyUtils.isEmpty(customerResponses)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "获取客户信息失败");
        }
        //获取 主数据cusBaseIds
        customerBaseIds = customerResponses.stream().map(CustomerResponse::getCustomerBaseId).collect(Collectors.toList());

        return customerBaseIds;
    }

}
